/**
 * Created by wry on 2014/12/11.
 */

var questionService = require('../services/questionService');
var messageUtil = require('../common/utils/messageUtil');
var toolUtil = require('../common/utils/toolUtil');
var nodeExcel = require('excel-export');

exports.postQuestionNew = function (req, res) {
    var input = req.body;
    var token = req.params.token;

    logger.info(req.files);

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            logger.error('postQuestionNew - uploadImage - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, '发起问题失败'));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (var i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            input['images'] = tempImages;

            questionService.postQuestionNewService(token, input, function (err, result) {
                if (err) {
                    logger.error('postQuestionNew - - ' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, '发起问题失败'));
                    toolUtil.deleteImage(images);
                } else {
                    var data = {
                        _id: result.question._id
                    };
                    toolUtil.hessianInvokeAddScore(token, 'postQuestion', function (score) {
                        if (score != null && score.currentValue != null) {
                            data.currentValue = score.currentValue;
                        }
                        res.json(messageUtil.composeSucceededMessage(req, null, data));

                        questionService.pushQuestionService(result.user, result.tag, result.tags, result.question, result.input, result.pushFlag);
                    });
                }
            });
        }
    });
};


/**
 * 增加提问
 */
exports.postQuestion = function (req, res) {
    var input = req.body;
    var token = req.params.token;
    questionService.postQuestionService(token, input, function (err, results) {
        if (err) {
            logger.error("Failed to post question - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to post question - " + err.message));
        } else {
            logger.debug("Succeeded to post a question! - " + results._id);

            res.json(messageUtil.composeSucceededMessage(req, null, results));

        }
    });
};

/**
 * 上传问题图片
 */
exports.uploadQuestionImages = function (req, res) {
    var objectName = 'question';
    var questionId = req.params.questionId;
    toolUtil.uploadImageService(objectName, questionId, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload question Images... - ' + err.message));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            questionService.setImagesToQuestion(questionId, tempImages, function (err, result) {
                if (err || tempImages == null) {
                    res.json(messageUtil.composeFailedMessage(req, 'Failed to upload question Images... - ' + err.message));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, null));
                }
            });
        }
    })
};
/**
 * 修改问题
 */
exports.updateQuestion = function (req, res) {
    var questionId = req.params.questionId;
    var input = req.body;

    logger.debug('Updating a Question: ' + questionId);

    questionService.updateQuestionService(questionId, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update the question data...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the question data...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

/**
 * 举报问题
 */
exports.reportQuestion = function (req, res) {
    var questionId = req.params.questionId;
    var token = req.params.token;
    questionService.reportQuestionService(token, questionId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update the question data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, '举报成功，请等待审核', null));
        }
    })
}

/**
 * 删除提问
 */
exports.deleteQuestion = function (req, res) {
    var questionId = req.params.questionId;
    var delDesc = req.params.delDesc;
    var input = req.body;
    logger.debug('Deleting a Question: ' + questionId);
    logger.debug(input);
    questionService.deleteQuestionService(questionId, delDesc,input,function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the question ...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the question...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 删除提问(自运营)
 */
exports.deleteQuestionByModerator = function (req, res) {
    var questionId = req.body.questionId;
    var delDesc = req.body.delDesc;
    var input = req.body;
    logger.debug('Deleting a Question: ' + questionId);
    logger.debug('req.body'+req.body);
    questionService.deleteQuestionByModerator(questionId,delDesc,input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the question ...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the question...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })

    questionService.updateQuestionReports(questionId,1,function(error) {
        console.log(error);
    });
};


/**
 * 删除提问图片
 */
exports.deleteQuestionImages = function (req, res) {
    var questionId = req.params.questionId;
    var images = req.body;
    logger.debug('Deleting a Question images: ' + questionId);

    questionService.deleteQuestionImagesService(questionId, images, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the question images ...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the question images...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 回答问题
 */
exports.postReply = function (req, res) {
    var questionId = req.params.questionId;
    var token = req.params.token;
    var input = req.body;

    logger.debug('Reply a question....' + questionId);

    questionService.postReplyService(token, questionId, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to postReply ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var replyId = {
                "_id": result.replies[result.replies.length - 1]._id
            };

            toolUtil.hessianInvokeAddScore(token, 'postReply', function (score) {
                if (score != null && score.currentValue != null) {
                    replyId.currentValue = score.currentValue;
                }
                res.json(messageUtil.composeSucceededMessage(req, null, replyId));
            });

            if (input.uList != null && input.uList.length > 0) {

            }
        }
    });
};

exports.postReplyNew = function (req, res) {
    var questionId = req.params.questionId;
    var token = req.params.token;
    var input = req.body;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            logger.error('postQuestionNew - uploadImage - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, '回复失败'));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (var i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            input['images'] = tempImages;

            questionService.postReplyNewService(token, questionId, input, function (err, result) {
                if (err) {
                    logger.error('Exception happened when postActivityReply ...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message));
                } else {
                    var replyId = {
                        "_id": result[9].replies[result[9].replies.length - 1]._id
                    };
                    toolUtil.hessianInvokeAddScore(token, 'postReply', function (score) {
                        if (score != null && score.currentValue != null) {
                            replyId.currentValue = score.currentValue;
                        }
                        res.json(messageUtil.composeSucceededMessage(req, null, replyId));
                    });

                    if (input.uList != null && typeof input.uList == 'string') {
                        input.uList = [input.uList];
                    }

                    //@功能
                    if (input.uList != null && input.uList.length > 0 && input.replyDesc.indexOf(atFlag) != -1) {
                        questionService.replyAtService(result[0], replyId._id, input.uList, 'question', token, input.replyDesc);
                    }

                    //推送
                    toolUtil.putMessageQAMQ({
                        msgType: 'reply',
                        isExistAt: input.uList != null && input.uList.length > 0 ? 1 : 0,
                        atUidList: input.uList,
                        replyUid: token,
                        topicId: result[0]._id + '',
                        replyId: replyId._id + '',
                        replyDesc: input.replyDesc,
                        contentType: 'question',
                        isAsk: input.replyTo == null ? 0 : 1,
                        toReplyUid: input.replyTo
                    });

                    //敏感词过滤
                    if (input.replyDesc != null && input.replyDesc != '') {
                        toolUtil.filteringSensitiveWords(result[0]._id, replyId._id, input.replyDesc, 'question');
                    }

                }
            })
        }
    });
};


exports.getCategoryQuestionCount = function (req, res) {
    var token = req.params.token;
    var category = req.params.category;

    questionService.getCategoryQuestionCountService(token, category, function (err, result) {
        if (err) {
            logger.error('getCategoryQuestionCountService' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
}

exports.getCommunityQuestionAndReplyCount = function (req, res) {
    var token = req.params.token;
    var tagId = req.params.tagId;
    questionService.getCommunityQuestionAndReplyCountService(token, tagId, function (err, result) {
            if (err) {
                logger.error(err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }
        }
    )
};

/**
 * 感谢回复
 */
exports.thankReply = function (req, res) {
    var questionId = req.params.questionId;
    var replyId = req.params.replyId;
    var replyBy = req.params.replyBy;
    var token = req.params.token;

    questionService.thankReplyService(questionId, replyId, replyBy, token, function (err, result) {
        if (err) {
            logger.error(err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, '感谢成功', result));
        }
    })
};

/**
 * 上传回答图片
 */
exports.uploadReplyImages = function (req, res) {
    var questionId = req.params.questionId;
    var replyId = req.params.replyId;
    var objectName = 'Replies';

    toolUtil.uploadImageService(objectName, replyId, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload reply Images... - ' + err.message));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            questionService.setImagesToReply(questionId, replyId, tempImages, function (err, result) {
                if (err || tempImages == null) {
                    res.json(messageUtil.composeFailedMessage(req, 'Failed to upload reply Images... - ' + err.message));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, null));
                }
            });
        }
    })
};
/**
 * 修改回答
 */
exports.updateReply = function (req, res) {
    var questionId = req.params.questionId;
    var replyId = req.params.replyId;
    var input = req.body;

    logger.debug('Updating a reply: ' + 'questionId=' + questionId + '-----replyId=' + replyId);

    questionService.updateReplyService(questionId, replyId, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update the reply data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the reply data...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

/**
 * 删除回答
 */
exports.deleteReply = function (req, res) {
    var questionId = req.params.questionId;
    var replyId = req.params.replyId;
    var token = req.params.token;
    logger.debug('Deleting a reply: ' + 'questionId=' + questionId + '-----replyId=' + replyId);

    questionService.deleteReplyService(token, questionId, replyId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the reply data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the reply data...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

/**
 * 删除回答图片
 */
exports.deleteReplyImages = function (req, res) {
    var questionId = req.params.questionId;
    var replyId = req.params.replyId;
    var images = req.body;
    logger.debug('Deleting a reply images: ' + replyId);

    questionService.deleteReplyImagesService(questionId, replyId, images, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the reply images ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the reply images...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

/**
 * 采纳回答
 */

exports.adoptReply = function (req, res) {
    var questionId = req.params.questionId;
    var replyId = req.params.replyId;
    var token = req.params.token;

    questionService.adoptReplyService(token, questionId, replyId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to adopting a reply...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            res.json(messageUtil.composeSucceededMessage(req, null, null));

            toolUtil.hessianInvokeAddScore(result, 'adoptReply', function (score) {

            });
        }
    });
};

/**
 * 创建投票
 */
exports.createPoll = function (req, res) {
    var token = req.params.token;
    var input = req.body;
    logger.debug('Creating a poll...');

    questionService.createPollService(token, input, function (err, result) {
        if (err) {
            logger.error("Failed to post poll - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to post poll - " + err.message));
        } else {
            logger.debug("Succeeded to post a poll! - " + result._id);

            var questionId = {
                "_id": result._id
            };
            res.json(messageUtil.composeSucceededMessage(req, null, questionId));
        }
    })
};

/**
 * 上传投票图片
 */
exports.uploadPollImages = function (req, res) {
    var objectName = 'Poll';
    var pollId = req.params.pollId;
    toolUtil.uploadImageService(objectName, pollId, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload poll Images... - ' + err.message));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            questionService.setImagesToQuestion(pollId, tempImages, function (err, result) {
                if (err || tempImages == null) {
                    res.json(messageUtil.composeFailedMessage(req, 'Failed to upload poll Images... - ' + err.message));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, null));
                }
            });
        }
    })
};

/**
 * 修改投票
 */
exports.updatePoll = function (req, res) {
    var pollId = req.params.pollId;
    var input = req.body;

    logger.debug('Updating a Poll: ' + pollId);

    questionService.updatePollService(pollId, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update the Poll data...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the Poll data...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

/**
 * 删除投票
 */
exports.deletePoll = function (req, res) {
    var pollId = req.params.pollId;
    logger.debug('Deleting a Poll: ' + pollId);

    questionService.deleteQuestionService(pollId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the poll ...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the poll...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
}

/**
 * 删除投票图片
 */
exports.deletePollImage = function (req, res) {
    var pollId = req.params.pollId;
    var images = req.body;
    logger.debug('Deleting a Poll images: ' + pollId);

    questionService.deleteQuestionImagesService(pollId, images, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the poll images ...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the poll images...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 投票
 */
exports.doPoll = function (req, res) {
    var pollId = req.params.pollId;
    var input = req.body;
    var token = req.params.token;

    questionService.doPollService(pollId, input, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to poll ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 关闭投票
 */
exports.closePoll = function (req, res) {
    var pollId = req.params.pollId;

    questionService.closePollService(pollId, function (err, result) {
        if (err) {
            logger.error('Exception happened when close a poll ...!' + pollId);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when close a poll...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 获取我的提问列表
 * @param req
 * @param res
 */
exports.getMyQuestionAndPollList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getMyQuestionAndPollListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get QuestionAndPollList ...!' + token);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get QuestionAndPollList...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};

exports.getMyQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getMyQuestionListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get getMyQuestionList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getMyReplyList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getMyReplyListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get getMyReplyList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 获取我所回复的提问列表
 * @param req
 * @param res
 */
exports.getMyRepliedQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getMyRepliedQuestionListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get QuestionAndPollList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get QuestionAndPollList...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};

/**
 * 获取问题详情
 * @param req
 * @param res
 */
exports.getDetailOfQuestionOrPoll = function (req, res) {
    var questionOrPollId = req.params.questionOrPollId;
    var token = req.params.token;

    questionService.getDetailOfQuestionOrPollService(token, questionOrPollId, function (err, result) {
        if (err) {
            logger.error('Exception happened when get a QuestionAndPoll ...!' + questionOrPollId + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getDetailOfQuestion = function (req, res) {
    var questionOrPollId = req.params.questionId;
    var token = req.params.token;
    var clickSource = req.cparams.clickSource;

    questionService.getDetailOfQuestionService(token, questionOrPollId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getDetailOfQuestion ...!' + questionOrPollId + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));

            if (clickSource != null) {
                var message = {
                    userId: token,
                    contentId: questionOrPollId,
                    type: 1,
                    clickSource: clickSource,
                    typeDesc: '话题',
                    createTime: new Date().getTime()
                }
                toolUtil.putMessageLogMQ(message);
            }
        }
    })
};

exports.getDetailReplyOfQuestion = function (req, res) {
    var page = req.params.page;
    var token = req.params.token;
    var questionId = req.params.questionId;
    var vcode = req.cparams.vcode;

    questionService.getDetailReplyOfQuestionService(page, token, questionId, vcode, function (err, results) {
        if (err) {
            logger.error('Exception happened when getDetailReplyOfQuestion ...!' + questionId + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};

exports.praiseReplyService = function (req, res) {
    var replyId = req.params.replyId;
    var token = req.params.token;
    var replyBy = req.params.replyBy;

    questionService.praiseReplyService(replyId, replyBy, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when praise a reply ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 获取专题详情
 * @param req
 * @param res
 */


/**
 * 问题置顶
 */
exports.moveQuestionToTop = function (req, res) {
    var opt = req.body;

    questionService.moveQuestionToTopService(opt, function (err, result) {
        if (err) {
            logger.error('Exception happened when move question or poll to top ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 取消置顶
 */
exports.cancelTopQuestion = function (req, res) {
    var input = req.body;

    questionService.cancelTopQuestionService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when cancelTopQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when cancelTopQuestion...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

/**
 * 回复置顶
 */
exports.moveReplyToTop = function (req, res) {
    var questionId = req.params.questionId;
    var replyId = req.params.replyId;

    questionService.moveReplyToTopService(questionId, replyId, function (err, result) {
        if (err) {
            logger.error('Exception happened when move reply to top ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when move reply to top...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 *  获取推荐给我的问题和投票列表
 */
exports.getRecommendedQuestionAndPollList = function (req, res) {
    var token = req.params.token;

    questionService.getRecommendedQuestionAndPollListService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get recommended question and poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get recommended question and poll list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 获取小区所有问题列表
 */
exports.getAllCommunityQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getAllCommunityQuestionListService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get all question list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get all question list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getAllCommunityQuestionListNew = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;

    <!--  宝宝树66小区二次改造    add   gct  20170808   start   -->
    var flag=req.params.flag;
    var communityId=req.params.communityId;
    <!--  宝宝树66小区二次改造    add   gct  20170808   end   -->
    var level;
    if (req.cparams != null && req.cparams.level != null) {
        level = Number(req.cparams.level);
    }
    var opt = {};
    if (req.cparams && req.cparams.level == 1) {
        opt.level = 1;
    }

    if (req.cparams && req.cparams.noreply == 1) {
        opt['$or'] = [{replies:{$exists: false}},{replies:{$size: 0}}];
    }


    if (req.cparams && req.cparams.noreply_t == 1) {
        var time = new Date(new Date().getTime() - 10 * 60 * 1000);
        opt['$or'] = [{replies:{$exists: false}},{replies:{$size: 0}}];
        opt.dateCreated = {$lt: time};
    }
    //1 未采纳 0.采纳
    if (req.cparams && req.cparams.noadopt == 1) {
        opt.replyStatus = req.cparams.noadopt;
    }

    /****
     * 被举报的帖子列表
     * @type {boolean} 判断是否筛选出举报帖子，忽视其他条件
     */
    opt.isReported = false;
    if (req.cparams && req.cparams.reported == 1) {
        opt.isReported = true;
    }

    console.log("全部");
    console.log(opt);
    questionService.getAllCommunityQuestionListNewService(ts, token, level,opt,flag,communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getAllCommunityQuestionListNew ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var ts = null;
            if(result) {
                ts = result.length > 0 ? result[result.length - 1]['dateCreated'].getTime() : (new Date("2000/04/01 00:00:00")).getTime();
            }
            var data = {
                ts: ts,
                all: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.getQuestionListByTag = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;
    var tagId = req.params.tagId;

    questionService.getQuestionListByTagService(ts, tagId, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getQuestionListByTag ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1].dateLastModified.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                tagList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

/**
 * 获取小区所有投票
 */
exports.getAllCommunityPollList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getAllCommunityPollListService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get all poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get all poll list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 获取小区专题列表
 */
exports.getAllCommunitySpecialTopicList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getAllCommunitySpecialTopicListService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get all SpecialTopic list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get all SpecialTopic list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};


/**
 * 根据分类获取问题和投票列表
 */
exports.getCategorizedQuestionAndPollList = function (req, res) {
    var tagId = req.params.tagId;
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getCategorizedQuestionAndPollListService(page, tagId, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get categorized question and poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get categorized question and poll list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 搜索列表
 * @param req
 * @param res
 */
exports.searchQuestionAndPollList = function (req, res) {
    var token = req.params.token;
    var keyword = req.params.keyword;

    questionService.searchQuestionAndPollListService(keyword, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when search question and poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
}

/**
 * 获取专家回答的问题
 */
exports.getExpertRepliedQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getExpertRepliedQuestionListService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get expert question and poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get expert question and poll list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 获取最新问题
 */
exports.getLatestQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;
    questionService.getLatestQuestionListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get community latest question list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get community latest question list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 获取达人排行榜
 */
exports.getTalentList = function (req, res) {
    var token = req.params.token;
    var tagId = req.params.tagId;

    questionService.getTalentListService(tagId, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get talent list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get talent list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

//===============================新版求助=========================
exports.getCategoryQuestionList = function (req, res) {
    var token = req.params.token;
    var category = req.params.category;
    var page = req.params.pageNo;

    questionService.getCategoryQuestionListService(token, category, page, function (err, results) {
        if (err) {
            logger.error('Exception happened when getCategoryQuestionList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getCategoryQuestionList...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};
/*  宝宝树66小区二次改造    add   gct  20170807   start   */
exports.getCommunityByUserID=function(req,res)
{
    var token = req.params.token;
    questionService.getCommunityByUserID(token,function(err,result){
        if (err) {
            logger.error('Exception happened when getCommunityAll ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            /*  var data = {
             // ts: result.length > 0 ? result[result.length - 1]['dateCreated'].getTime() : new Date("2000/04/01 00:00:00").getTime(),
             categoryList: result
             };*/
            /*  for(var i=0;i<result.length;i++)
             {
             var ri=result[i];
             console.log(ri);
             }*/
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
}
/*  宝宝树66小区二次改造    add   gct  20170807   end   */

/*  宝宝树66小区二次改造    add   gct  20170804   start   */
exports.getCommunityAll = function (req, res) {
    var token = req.params.token;

    questionService.getCommunityAllService(token,function (err, result) {
            if (err) {
                logger.error('Exception happened when getCommunityAll ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            /*  var data = {
                   // ts: result.length > 0 ? result[result.length - 1]['dateCreated'].getTime() : new Date("2000/04/01 00:00:00").getTime(),
                    categoryList: result
                };*/
              /* for(var i=0;i<result.length;i++)
                {
                    var ri=result[i];
                    console.log(ri);
                }*/
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }
        }
    )
}


/*  宝宝树66小区二次改造    add   gct  20170804   end   */



exports.getCategoryQuestionListNew = function (req, res) {
    var token = req.params.token;
    var category = req.params.category;
    var ts = req.params.ts;
    /*  宝宝树66小区二次改造    add   gct  20170808   start   */
    var flag=req.params.flag;
    var communityId=req.params.communityId;
    /*  宝宝树66小区二次改造    add   gct  20170808   end   */
    questionService.getCategoryQuestionListNewService(req, token, category, ts,flag,communityId, function (err, result) {
            if (err) {
                logger.error('Exception happened when getCategoryQuestionListNew ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
            } else {

                var data = {
                    ts: result.length > 0 ? result[result.length - 1]['dateCreated'].getTime() : new Date("2000/04/01 00:00:00").getTime(),
                    categoryList: result
                };
                res.json(messageUtil.composeSucceededMessage(req, null, data));
            }
        }
    )
}


//====================================Web端===============================

/**
 * question-controller.js
 * 创建问题
 * author:chenjinzhuan
 */
exports.createQuestion = function (req, res) {
    var input = req.body;
    questionService.createQuestionService(input, function (err, result) {
        if (err) {
            logger.error("Failed to create RESTFull service - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to post question - " + err.message));
        } else {
            logger.debug("Succeeded to create RESTFull service! - " + result._id);
            res.json(messageUtil.composeSucceededMessage(req, null, result._id));
        }
    });
}

/**
 * question-controller.js
 * 更新问题
 * author:chenjinzhuan
 */
exports.backOfficeUpdateQuestion = function (req, res) {

    var id = req.params.objId;
    var input = req.body;

    questionService.updateOneQuestionService(id, input, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to update the Question data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the Question  data...!'));
        } else {
            if (results != 0) {
                logger.debug("Update Question  successfully...!");
                res.json(messageUtil.composeSucceededMessage(req, null, null));

                if (input.tag != null) {
                    toolUtil.putMessageQAMQ({
                        msgType: 'hobby',
                        questionId: id + '',
                        contentType: 'question'
                    });
                }

            } else {
                logger.error('Failed to update the Question , it is not existing! -' + id);
                res.json(messageUtil.composeFailedMessage(req, 'Failed to update the Question , it is not existing! -' + id));
            }
        }
    })
};

/**
 * question-controller.js
 * 更新问题
 * author:chenjinzhuan
 */
exports.backOfficeUpdateQuestionByModerator = function (req, res) {

    var id = req.params.objId;
    var input = req.body;

    questionService.backOfficeUpdateQuestionByModerator(id, input, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to update the Question by Moderator data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the Question  data...!'));
        } else {
            if (results != 0) {
                logger.debug("Update Question  successfully...!");
                res.json(messageUtil.composeSucceededMessage(req, null, null));

                if (input.tag != null) {
                    toolUtil.putMessageQAMQ({
                        msgType: 'hobby',
                        questionId: id + '',
                        contentType: 'question'
                    });
                }

            } else {
                logger.error('Failed to update the Question , it is not existing! -' + id);
                res.json(messageUtil.composeFailedMessage(req, 'Failed to update the Question , it is not existing! -' + id));
            }
        }
    })
};

/**
 * question-controller.js
 * 获取问题列表
 * author:chenjinzhuan
 */
exports.getQuestionList = function (req, res) {

    questionService.getQuestionListService(function (err, results) {
        if (err) {
            logger.error('Exception happened when get Question List ...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get Question List...!'));
        } else {
            logger.debug("get Question List  successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });

};

/**
 * question-controller.js
 * 根据条件查找问题列表
 * author:chenjinzhuan
 */
exports.searchQuestion = function (req, res) {

    var question = req.body;
    logger.debug('question:' + question);

    questionService.searchQuestionService(question, function (err, results) {
        if (err) {
            logger.error('Exception happened when search Question...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when search Question...!'));
        } else {
            logger.debug("search Question successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });

};

/**
 * question-controller.js
 * 通过Id获取问题
 * author:chenjinzhuan
 */
exports.getQuestionById = function (req, res) {
    var id = req.params.objId;
    questionService.getQuestionByIdService(id, function (err, results) {
        if (err) {
            logger.error('Exception happened when get question by Id ...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get question by Id...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });

};

/**
 * question-controller.js
 * 删除问题
 * author:chenjinzhuan
 */
exports.deleteOneQuestion = function (req, res) {

    var id = req.params.objId;
    questionService.deleteOneQuestionService(id, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to delete one question...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete one question...!'));
        } else {
            if (results != null) {
                logger.debug("Delete one question  successfully...!");
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            } else {
                logger.error('Failed to delete one question, it is not existing! -' + id);
                res.json(messageUtil.composeFailedMessage(req, 'Failed to delete one question , it is not existing! -' + id));
            }
        }
    })
};

/**
 * question-controller.js
 * 修改问题顺序
 * author:chenjinzhuan
 */
exports.changeQuestionOrder = function (req, res) {
    var question = req.body;
    questionService.changeQuestionOrderService(question, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to change question order...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to change question order...!'));
        } else {
            if (results != null) {
                logger.debug("Change question order successfully...!");
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            } else {
                logger.error('Failed to change question order, it is not existing! -' + id);
                res.json(messageUtil.composeFailedMessage(req, 'Failed to change question order, it is not existing! -'));
            }
        }
    })
};


/**
 * question-controller.js
 * 获取问题列表
 * author:chenjinzhuan
 */
exports.getReplyList = function (req, res) {
    var questionId = req.params.questionOrPollId;
    //var token = req.params.token;

    questionService.getReplyListService(questionId, function (err, result) {
        if (err) {
            logger.error('Exception happened when get a QuestionAndPoll ...!' + questionOrPollId + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get a QuestionAndPoll...!' + err.message));
        } else {
            //logger.debug(result.replies);
            res.json(messageUtil.composeSucceededMessage(req, null, result.replies));
        }
    })
};


/**
 * question-controller.js
 * 根据条件查找回复列表
 * author:chenjinzhuan
 */
exports.searchReply = function (req, res) {

    var input = req.body;
    logger.debug('input:' + input);

    questionService.searchReplyService(input, function (err, results) {
        if (err) {
            logger.error('Exception happened when search Question...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when search Question...!'));
        } else {
            logger.debug("search Question successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });

};

/**
 * question-controller.js
 * 删除回答
 * author:chenjinzhuan
 */
exports.deleteReplyByPost = function (req, res) {

    var input = req.body;
    var questionId = input.questionId;
    var replyId = input.replyId;

    logger.debug('Deleting a reply: ' + 'questionId=' + questionId + '-----replyId=' + replyId);

    questionService.deleteReplyService(questionId, replyId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the reply data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the reply data...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

exports.getNoReplyQuestionList = function (req, res) {
    var communityId = req.params.objId;


    questionService.getNoReplyQuestionListService(communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to getNoReplyQuestionList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to getNoReplyQuestionList...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.backOfficePostReply = function (req, res) {
    var questionId = req.params.objId;
    var input = req.body;


    questionService.backOfficePostReplyService(questionId, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the question images ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the question images...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

exports.getReportQuestion = function (req, res) {
    var communityId = req.params.communityId;

    questionService.getReportQuestionService(communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to getReportQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to getReportQuestion...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.deleteReportQuestion = function (req, res) {
    var questionId = req.params.questionId;

    questionService.deleteReportQuestionService(questionId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to deleteReportQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to deleteReportQuestion...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};


exports.exportQuestionList = function (req, res) {
    var input = req.cparams;
    logger.error(input);
    var page = req.params.page;
    var size = req.params.size;


    questionService.exportQuestionListService(input, page, size, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to exportQuestionList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to exportQuestionList...!'));
        } else {
            //var data = {
            //    totalPage: results[1],
            //    questionList: results[2]
            //};

            var data = results[2];
            var conf = {};

            conf.cols = [{
                caption: '所属小区',
                type: 'String'
            }, {
                caption: '板块内小区',
                type: 'String'
            }, {
                caption: '标签',
                type: 'String'
            }, {
                caption: '浏览次数',
                type: 'String'
            }, {
                caption: '描述',
                type: 'String'
            }, {
                caption: '回复/数量',
                type: 'String'
            }, {
                caption: '创建者',
                type: 'String'
            }, {
                caption: '发布时间',
                type: 'String'
            }, {
                caption: '最后修改时间',
                type: 'String'
            }, {
                caption: '分类',
                type: 'String'
            }];


            var tempRows = new Array();

            for (var i = 0; i < data.length; i++) {

                var temp = new Array();
                temp.push(data[i].community.communityName);


                var around = "";
                if(data[i].aroundCommunity != null){
                    for(var j = 0 ; j < data[i].aroundCommunity.length ; j++){
                        if(j == 0){
                            around += data[i].aroundCommunity[j];
                        }else{
                            around += ","+data[i].aroundCommunity[j];
                        }
                    }
                }
                temp.push(around != "" ? around : "");


                var tags = "";
                if(data[i].tag != null){
                    for(var j = 0 ; j < data[i].tag.length ; j++){
                        if(j == 0){
                            tags += data[i].tag[j];
                        }else{
                            tags += ","+data[i].tag[j];
                        }
                    }
                }
                temp.push(tags != "" ? tags : "");


                temp.push(data[i].browserCount+"");
                logger.info(data[i].browserCount);
                temp.push(data[i].desc);
                temp.push(data[i].replies.length+"");
                temp.push(data[i].createdBy.nickName);

                if (data[i].dateCreated != null) {
                    var dateCreated = new Date(data[i].dateCreated);
                    temp.push(dateCreated.getFullYear() + "-" + (dateCreated.getMonth() + 1) + "-" + dateCreated.getDate() + " " + dateCreated.getHours() + ":" + dateCreated.getMinutes());
                } else {
                    temp.push("");
                }

                if (data[i].dateLastModified != null) {
                    var dateLastModified = new Date(data[i].dateLastModified);
                    temp.push(dateLastModified.getFullYear() + "-" + (dateLastModified.getMonth() + 1) + "-" + dateLastModified.getDate() + " " + dateLastModified.getHours() + ":" + dateLastModified.getMinutes());
                } else {
                    temp.push("");
                }

                temp.push(questionCategory[data[i].category]);
                tempRows.push(temp);
            }
            conf.rows = tempRows;

            var ret = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
            res.end(ret, 'binary');

            //res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
}



// 问题列表
exports.getRecommendQuestion = function (req, res) {
    var opt = req.body;
    var page = req.params.page;
    var size = req.params.size;

    //if (opt.tag == '有标签') {
    //    opt.tag = {$exists: true};
    //    opt.$where = "this.tag.length>0"
    //} else if (opt.tag == '无标签') {
    //    opt.tag = {$size: 0};
    //}

    questionService.getRecommendQuestionService(opt, page, size, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to getRecommendQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to getRecommendQuestion...!'));
        } else {
            var data = {
                totalPage: results[1],
                questionList: results[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.recommendQuestion = function (req, res) {
    var questionId = req.params.questionId;
    var flag = req.params.flag;

    questionService.recommendQuestionService(questionId, flag, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to recommendQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to recommendQuestion...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.searchUserQuestion = function (req, res) {
    var userId = req.params.userId;

    questionService.searchUserQuestionService(userId, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to searchUserQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to searchUserQuestion...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};


exports.getFreshNewsQuestion = function (req, res) {
    questionService.getFreshNewsQuestionService(function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to getFreshNewsQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to getFreshNewsQuestion...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.addQuestionToFreshNews = function (req, res) {
    var input = req.body;
    questionService.addQuestionToFreshNewsService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to addQuestionToFreshNews ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to addQuestionToFreshNews...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.pushQuestionByTag = function (req, res) {
    var question = req.body;

    questionService.pushQuestionByTagService(question, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to pushQuestionByTag ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to pushQuestionByTag...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.confirmPushQuestion = function (req, res) {

    var question = req.body.question;
    var data = req.body.uList;

    //个推
    var content = {
        type: 1,
        flag: 2,
        openType: 1,
        contentId: question._id,
        createdBy: question.createdBy._id,
        desc: question.createdBy.nickName + ':' + question.desc
    };
    var pushData = {
        uList: data,
        content: content,
        type: 'operate',
        tag: '话题'
    };
    toolUtil.putMessageGetuiPushMQ(pushData);

    res.json(messageUtil.composeSucceededMessage(req, null, null));
}

exports.changeQuestionCategory = function (req, res) {
    var questionId = req.params.questionId;
    var category = req.params.category;

    questionService.changeQuestionCategoryService(questionId, category, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to changeQuestionCategory ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to changeQuestionCategory...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.changeQuestionLevel = function (req, res) {
    var input = req.body;

    questionService.changeQuestionLevelService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to changeQuestionLevelService ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            if(input.level == 1) {
                //个推
                var content = {
                    type: 1,
                    flag: 2,
                    openType: input.openType,
                    contentId: input.questionId,
                    createdBy: input.userId,
                    desc: input.desc
                };
                var pushData = {
                    uList: [input.userId],
                    content: content,
                    ip: req.headers['X-Real-IP'],
                    tag: input.tag,
                    type: 'operate'
                };
                //logger.debug(pushData);
                toolUtil.putMessageGetuiPushMQ(pushData);

            }
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
}


exports.getQuestionByFilter = function (req, res) {
    var opt = req.body;

    //logger.debug(opt);
    questionService.getQuestionByFilter(opt, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to getQuestionByFilter ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to getQuestionByFilter...!'));
        } else {
            //logger.debug(results);
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};